package com.doublethread.easymart.modules.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doublethread.easymart.common.exception.OrderException;
import com.doublethread.easymart.common.exception.ProductException;
import com.doublethread.easymart.modules.cart.dto.CartAddDTO;
import com.doublethread.easymart.modules.cart.dto.CartUpdateDTO;
import com.doublethread.easymart.modules.cart.entity.Cart;
import com.doublethread.easymart.modules.cart.mapper.CartMapper;
import com.doublethread.easymart.modules.cart.service.CartService;
import com.doublethread.easymart.modules.cart.vo.CartVO;
import com.doublethread.easymart.modules.product.entity.Product;
import com.doublethread.easymart.modules.product.mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车服务实现类
 */
@Slf4j
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<CartVO> getUserCartList(Long userId) {
        log.info("获取用户购物车列表");

        // 查询用户购物车
        List<Cart> cartList = this.list(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getStatus, 1)
                .orderByDesc(Cart::getCreateTime));

        // 转换为VO
        List<CartVO> cartVOList = cartList.stream()
                .map(this::convertToCartVO)
                .toList();

        log.info("获取用户购物车列表成功");
        return cartVOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addToCart(Long userId, CartAddDTO cartAddDTO) {
        log.info("添加商品到购物车");

        // 检查商品是否存在且上架
        Product product = productMapper.selectById(cartAddDTO.getProductId());
        if (product == null) {
            ProductException.productNotFound();
        }
        if (product.getStatus() != 1) {
            ProductException.productDisabled();
        }

        // 检查库存
        if (product.getStock() < cartAddDTO.getQuantity()) {
            ProductException.outOfStock();
        }

        // 检查购物车中是否已存在该商品
        Cart existingCart = this.getOne(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, cartAddDTO.getProductId())
                .eq(Cart::getStatus, 1));

        if (existingCart != null) {
            // 如果已存在，更新数量
            int newQuantity = existingCart.getQuantity() + cartAddDTO.getQuantity();
            if (newQuantity > product.getStock()) {
                ProductException.outOfStock();
            }

            existingCart.setQuantity(newQuantity);
            existingCart.setPrice(product.getPrice()); // 更新为当前价格
            this.updateById(existingCart);

            log.info("更新购物车商品数量");
        } else {
            // 如果不存在，新增购物车项 - 使用Builder模式
            Cart cart = Cart.builder()
                    .userId(userId)
                    .productId(cartAddDTO.getProductId())
                    .quantity(cartAddDTO.getQuantity())
                    .price(product.getPrice())
                    .status(1)
                    .build();
            this.save(cart);

            log.info("新增购物车商品");
        }

        log.info("添加商品到购物车成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCartItem(Long userId, Long cartId, CartUpdateDTO cartUpdateDTO) {
        log.info("更新购物车商品数量: userId={}, cartId={}, quantity={}",
                userId, cartId, cartUpdateDTO.getQuantity());

        // 检查购物车项是否存在且属于当前用户
        Cart cart = this.getById(cartId);
        if (cart == null || !cart.getUserId().equals(userId)) {
            OrderException.cartItemNotFound();
        }

        // 检查商品库存
        Product product = productMapper.selectById(cart.getProductId());
        if (product == null) {
            ProductException.productNotFound();
        }
        if (product.getStock() < cartUpdateDTO.getQuantity()) {
            ProductException.outOfStock();
        }

        // 更新数量和价格
        cart.setQuantity(cartUpdateDTO.getQuantity());
        cart.setPrice(product.getPrice()); // 更新为当前价格
        this.updateById(cart);

        log.info("更新购物车商品数量成功: cartId={}, quantity={}", cartId, cartUpdateDTO.getQuantity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCartItem(Long userId, Long cartId) {
        log.info("删除购物车商品: userId={}, cartId={}", userId, cartId);

        // 检查购物车项是否存在且属于当前用户
        Cart cart = this.getById(cartId);
        if (cart == null || !cart.getUserId().equals(userId)) {
            OrderException.cartItemNotFound();
        }

        // 直接删除购物车项（物理删除）
        this.removeById(cartId);

        log.info("删除购物车商品成功: cartId={}", cartId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCartItems(Long userId, List<Long> cartIds) {
        log.info("批量删除购物车商品: userId={}, cartIds={}", userId, cartIds);

        if (cartIds == null || cartIds.isEmpty()) {
            return;
        }

        // 检查所有购物车项是否属于当前用户
        List<Cart> carts = this.listByIds(cartIds);
        for (Cart cart : carts) {
            if (!cart.getUserId().equals(userId)) {
                OrderException.cartItemNotFound();
            }
        }

        // 批量直接删除（物理删除）
        this.removeByIds(cartIds);

        log.info("批量删除购物车商品成功: userId={}, 删除数量={}", userId, cartIds.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearUserCart(Long userId) {
        log.info("清空用户购物车: userId={}", userId);

        // 直接删除用户所有购物车项（物理删除）
        this.remove(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId));

        log.info("清空用户购物车成功: userId={}", userId);
    }

    @Override
    public Integer getCartItemCount(Long userId) {
        log.info("获取购物车商品总数量: userId={}", userId);

        // 统计用户购物车中的商品总数量
        List<Cart> cartList = this.list(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getStatus, 1));

        int totalCount = cartList.stream()
                .mapToInt(Cart::getQuantity)
                .sum();

        log.info("获取购物车商品总数量成功: userId={}, totalCount={}", userId, totalCount);
        return totalCount;
    }

    @Override
    public void checkCartStock(Long userId, List<Long> cartIds) {
        log.info("检查购物车商品库存: userId={}, cartIds={}", userId, cartIds);

        if (cartIds == null || cartIds.isEmpty()) {
            return;
        }

        // 查询购物车项
        List<Cart> carts = this.listByIds(cartIds);

        for (Cart cart : carts) {
            // 检查是否属于当前用户
            if (!cart.getUserId().equals(userId)) {
                OrderException.cartItemNotFound();
            }

            // 检查商品库存
            Product product = productMapper.selectById(cart.getProductId());
            if (product == null) {
                ProductException.productNotFound();
            }
            if (product.getStatus() != 1) {
                ProductException.productDisabled();
            }
            if (product.getStock() < cart.getQuantity()) {
                ProductException.outOfStock();
            }
        }

        log.info("检查购物车商品库存成功: userId={}", userId);
    }

    @Override
    public List<CartVO> getSelectedCartItems(Long userId, List<Long> cartIds) {
        log.info("获取选中的购物车商品: userId={}, cartIds={}", userId, cartIds);

        if (cartIds == null || cartIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 查询购物车项
        List<Cart> carts = this.list(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .in(Cart::getId, cartIds)
                .eq(Cart::getStatus, 1)
                .orderByDesc(Cart::getCreateTime));

        // 验证购物车项是否都属于当前用户
        if (carts.size() != cartIds.size()) {
            OrderException.cartItemNotFound();
        }

        // 转换为VO
        List<CartVO> cartVOList = carts.stream()
                .map(this::convertToCartVO)
                .toList();

        log.info("获取选中的购物车商品成功: userId={}, 商品数量={}", userId, cartVOList.size());
        return cartVOList;
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 转换Cart实体为CartVO
     */
    private CartVO convertToCartVO(Cart cart) {
        // 获取商品信息
        Product product = productMapper.selectById(cart.getProductId());

        if (product == null) {
            // 商品已删除，返回基本信息
            return CartVO.builder()
                    .id(cart.getId())
                    .productId(cart.getProductId())
                    .productName("商品已删除")
                    .productImage("")
                    .currentPrice(BigDecimal.ZERO)
                    .cartPrice(cart.getPrice())
                    .quantity(cart.getQuantity())
                    .subtotal(BigDecimal.ZERO)
                    .stock(0)
                    .productStatus(0)
                    .isValid(false)
                    .priceChanged(false)
                    .createTime(cart.getCreateTime())
                    .build();
        }

        // 计算小计金额
        BigDecimal subtotal = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));

        // 判断价格是否变动
        boolean priceChanged = !product.getPrice().equals(cart.getPrice());

        // 判断是否有效（商品上架且有库存且数量不超过库存）
        boolean isValid = product.getStatus() == 1 &&
                product.getStock() > 0 &&
                cart.getQuantity() <= product.getStock();

        return CartVO.builder()
                .id(cart.getId())
                .productId(cart.getProductId())
                .productName(product.getName())
                .productImage(product.getMainImage())
                .currentPrice(product.getPrice())
                .cartPrice(cart.getPrice())
                .quantity(cart.getQuantity())
                .subtotal(subtotal)
                .stock(product.getStock())
                .productStatus(product.getStatus())
                .isValid(isValid)
                .priceChanged(priceChanged)
                .createTime(cart.getCreateTime())
                .build();
    }
}
